package com.reny.git.imgload.glide

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import com.bumptech.glide.request.target.ImageViewTarget
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.reny.git.imgload.BlurTransformation
import com.reny.git.imgload.GlideRoundTransform
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File

class GlideLoader : ILoader {

    override fun display(
        view: View,
        model: Any?,
        owner: Any,
        header: HashMap<String, String>,
        radius: Int,
        isBlur: Boolean,
        placeHolder: Int,
        errorHolder: Int,
        fallbackHolder: Int
    ) {
        var reqManager: RequestManager = Glide.with(view)
        when (owner) {
            is FragmentActivity -> {
                reqManager = Glide.with(owner)
            }
            is Activity -> {
                reqManager = Glide.with(owner)
            }
            is Fragment -> {
                reqManager = Glide.with(owner)
            }
        }

        var req = reqManager
            .load(configUrlHeader(model, header))
            .apply {
                if(model != null && model is Int && placeHolder == ImgUtils.instance.placeHolder){
                    //加载本地图片，并且使用的默认占位图 就不设置占位
                } else {
                    placeholder(placeHolder)
                }
            }
            .error(errorHolder)
            .fallback(fallbackHolder)

        if (radius > 0) {
            req = req.transform(GlideRoundTransform(radius))//req.optionalCircleCrop().override(radius * 2)
            //req = req.optionalTransform(RoundedCorners(radius))
        }
        if (isBlur) {
            try {
                req = req.optionalTransform(
                    BlurTransformation(view.context)
                )
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        if (view is ImageView) {
            req.into(view)
        } else { //针对LinearLayout等控件设置背景
            req.intoBg(view)
        }
    }


    override fun displayTarget(
        view: ImageView,
        model: Any?,
        target: ImageViewTarget<Bitmap>,
        owner: Any
    ) {
        Glide.with(view)
            .asBitmap()
            .load(model)
            .into(target)
    }


    override fun cache(context: Context, model: Any?, width: Int?, height: Int?) {
        try {
            val req = Glide.with(context)
                .download(configUrlHeader(model))

            if (width != null && height != null) {
                req.preload(width, height)
            } else {
                req.preload()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }



    override fun displayCache(view: View, model: Any?) {
        try {
            val req = Glide.with(view)
                .load(configUrlHeader(model))
                .placeholder(ImgUtils.instance.placeHolder)
                .error(ImgUtils.instance.errorHolder)
                .fallback(ImgUtils.instance.fallbackHolder)
                .onlyRetrieveFromCache(true)
            if (view is ImageView) {
                req.into(view)
            } else {
                req.intoBg(view)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            //调用这个方法要求先调用cache  如果缓存被清理了 可能出现问题 这里兜底方案
            display(view, model)
        }
    }

    override fun loadBitmap(context: Context, model: Any?, callBack: (Bitmap?) -> Unit) {
        try {
            Glide.with(context)
                .asBitmap().load(configUrlHeader(model))
                .into(object : SimpleTarget<Bitmap?>() {
                    override fun onResourceReady(
                        resource: Bitmap,
                        transition: Transition<in Bitmap?>?
                    ) {
                        callBack(resource)
                    }
                    override fun onLoadFailed(errorDrawable: Drawable?) {
                        callBack(null)
                    }
                })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun loadDrawable(
        context: Context,
        model: Any?,
        callBack: (Drawable?) -> Unit
    ) {
        try {
            Glide.with(context)
                .asDrawable().load(configUrlHeader(model))
                .into(object : SimpleTarget<Drawable?>() {
                    override fun onResourceReady(
                        resource: Drawable,
                        transition: Transition<in Drawable?>?
                    ) {
                        callBack(resource)
                    }
                    override fun onLoadFailed(errorDrawable: Drawable?) {
                        callBack(null)
                    }
                })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun downLoadImg(context: Context, model: Any?, callBack: (File?) -> Unit) {
        try {
            GlobalScope.launch {
                Glide.with(context)
                    .download(configUrlHeader(model))
                    .into(object : SimpleTarget<File?>() {
                        override fun onResourceReady(
                            resource: File,
                            transition: Transition<in File?>?
                        ) {
                            callBack(resource)
                        }
                        override fun onLoadFailed(errorDrawable: Drawable?) {
                            callBack(null)
                        }
                    })
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    /*private suspend fun downLoadImgAsync(context: Context, model: Any?): File? {
        var file: File? = null
        try {
            Glide.with(context)
                .download(configUrlHeader(model))
                .into(object : SimpleTarget<File?>() {
                    override fun onResourceReady(
                        resource: File,
                        transition: Transition<in File?>?
                    ) {
                        file = resource
                    }
                    override fun onLoadFailed(errorDrawable: Drawable?) {}
                })
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return file
    }*/


    override fun pauseRequests(context: Context) {
        Glide.with(context).pauseRequests()
    }

    override fun resumeRequests(context: Context) {
        Glide.with(context).resumeRequests()
    }

}